
# ----------用于将netbox日期时间格式提取日期，方便比较
def change_datetime(date_time):
    """
    :param date_time: 2022-02-22T08:02:53.965582Z
    :return:
    """
    from datetime import datetime
    # 删除时区中间的冒号 +08:00 -> +0800
    if '+' in date_time:
        tmpdate = date_time.split('+', 1)
        tmpdate[1] = tmpdate[1].replace(':', '')
        tmpdate[1] = tmpdate[1].replace('^', '^[+]')
        date_time = tmpdate[0] + '+' + tmpdate[1]
    # 定义数据格式与输出格式
    netbox_format = '%Y-%m-%dT%H:%M:%S.%fZ'
    local = datetime.strptime(date_time, netbox_format)

    return local


# -----通用--带宽单位显示转换--0.0---------
def bandwidth_change(bandwidth, unit):
    """
    :param bandwidth:
    :param unit: [KB,MB,GB]
    :return:
    """
    from math import ceil
    # 统一转换为MB进行计算
    if bandwidth:
        if unit == "MB":
            pass
        elif unit == "KB":
            bandwidth = bandwidth / 1000
        elif unit == "GB":
            bandwidth = bandwidth * 1000
        elif unit == "B":
            bandwidth = bandwidth / 1000000
        else:
            return f"error:error unit:{unit},it should in ['B', 'KB', 'MB', 'GB']"
        # 向上取整
        bandwidth = ceil(bandwidth)
    # if bandwidth:  # 判断带宽字段是否为空
        if bandwidth >= 1000:  # 判断带宽是否>1000
            if bandwidth % 1000:
                ret = str(bandwidth / 1000) + 'G'
            else:
                ret = str(bandwidth // 1000) + 'G'
        else:
            ret = str(bandwidth) + 'M'
    else:
        ret = 'unknow'
    return ret